package com.peas.platform.common.core.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.peas.platform.common.core.configuration.FeignConfig;
import com.peas.platform.common.core.property.ProjectProperties;
import lombok.SneakyThrows;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class SystemTool {

    @Resource
    private ProjectProperties projectProperties;
    @Resource
    private ApplicationContext ac;
    @Resource
    private DiscoveryClient discoveryClient;

    public JSONObject buildJSONObject() {
        JSONObject data = new JSONObject();
        data.set("business", projectProperties.getBusiness());
        data.set("businessName", projectProperties.getBusinessName());
        data.set("service", projectProperties.getService());
        data.set("serviceName", projectProperties.getServiceName());
        return data;
    }

    public boolean special() {
        return StrUtil.equals(projectProperties.getService(), FeignConfig.core) || BooleanUtil.isTrue(projectProperties.getSingleton());
    }

    @SneakyThrows
    public List<Instance> getInstances() {
        List<String> services = discoveryClient.getServices();
        if (CollUtil.isEmpty(services)) {
            return null;
        }
        List<Instance> result = new ArrayList<>();
        for (String svc : services) {
            NacosServiceManager nacosServiceManager = ac.getBean(NacosServiceManager.class);
            List<Instance> instances = nacosServiceManager.getNamingService().getAllInstances(svc);
            if (CollUtil.isNotEmpty(instances)) {
                result.addAll(instances);
            }
        }
        return result;
    }

}
